<?php

namespace App\Listeners;

use App\Models\User\User;
use Overtrue\LaravelWeChat\Events\WeChatUserAuthorized;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class WechatUserMaintain
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  WeChatUserAuthorized  $event
     * @return void
     */
    public function handle(WeChatUserAuthorized $event)
    {
        $user = $event->user;
        $systemUser = User::query()->where('openid',$user->id)->first();

        $originalUser= $user->getOriginal();
        $originalUser = collect($originalUser);
        Log::channel('event')->info('进入微信事件系统',[$originalUser]);
        $userData = [
            'openid' => $originalUser['openid'],
            'nickName' => $originalUser['nickname'],
            'avatarUrl' => $originalUser['headimgurl'],
            'province' => $originalUser['province'],
            'city' => $originalUser['city'],
            'gender' => $originalUser['sex'],
        ];

        if (!$systemUser) {
            $user =  User::query()->create($userData);
        } else {
            $systemUser->update($userData);
        }

    }
}
